using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SeataNet.Core.Common;
using SeataNet.Core.Context;
using SeataNet.Core.Interceptor;
using SeataNet.Core.RPC;
using SeataNet.Core.Saga;

namespace SeataNet.Core.Saga
{
    /// <summary>
    /// Saga服务集合扩展
    /// </summary>
    public static class SagaServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Saga模式支持
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSagaMode(
            this IServiceCollection services,
            Action<SagaConfiguration>? configureAction = null)
        {
            // 添加配置
            if (configureAction != null)
            {
                services.Configure(configureAction);
            }
            else
            {
                services.Configure<SagaConfiguration>(config => { });
            }

            // 添加选项
            services.AddOptions();
            
            // 添加日志
            services.AddLogging();

            // 注册核心服务
            services.TryAddScoped<ISagaTransactionManager, DefaultSagaTransactionManager>();
            services.TryAddScoped<ISagaStateStore, InMemorySagaStateStore>();
            services.TryAddScoped<SagaTransactionAspect>();
            services.TryAddScoped<SagaTransactionTemplate>();

            // 注册拦截器
            services.TryAddTransient<IInterceptor, SagaTransactionInterceptor>();

            // 注册Saga服务基类
            services.AddTransient(typeof(SagaServiceBase));

            // 后期初始化
            services.AddSingleton<IHostedService, SagaInitializationService>();

            return services;
        }

        /// <summary>
        /// 添加Saga状态存储
        /// </summary>
        /// <typeparam name="TStateStore">状态存储实现类型</typeparam>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSagaStateStore<TStateStore>(this IServiceCollection services)
            where TStateStore : class, ISagaStateStore
        {
            services.Replace(ServiceDescriptor.Scoped<ISagaStateStore, TStateStore>());
            return services;
        }

        /// <summary>
        /// 添加文件Saga状态存储
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddFileSagaStateStore(
            this IServiceCollection services,
            Action<FileSagaStateStoreOptions>? configureAction = null)
        {
            if (configureAction != null)
            {
                services.Configure(configureAction);
            }
            
            services.Replace(ServiceDescriptor.Scoped<ISagaStateStore, FileSagaStateStore>());
            return services;
        }
    }

    /// <summary>
    /// Saga配置
    /// </summary>
    public class SagaConfiguration
    {
        /// <summary>
        /// 是否启用Saga模式
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 默认超时时间（毫秒）
        /// </summary>
        public int DefaultTimeout { get; set; } = 60000;

        /// <summary>
        /// 默认重试次数
        /// </summary>
        public int DefaultRetryCount { get; set; } = 3;

        /// <summary>
        /// 默认重试间隔（毫秒）
        /// </summary>
        public int DefaultRetryInterval { get; set; } = 1000;

        /// <summary>
        /// 状态存储配置
        /// </summary>
        public StateStoreConfiguration StateStore { get; set; } = new();

        /// <summary>
        /// 补偿配置
        /// </summary>
        public CompensationConfiguration Compensation { get; set; } = new();
    }

    /// <summary>
    /// 状态存储配置
    /// </summary>
    public class StateStoreConfiguration
    {
        /// <summary>
        /// 存储类型
        /// </summary>
        public StateStoreType StoreType { get; set; } = StateStoreType.InMemory;

        /// <summary>
        /// 文件存储路径
        /// </summary>
        public string FilePath { get; set; } = "saga-state";

        /// <summary>
        /// 数据清理间隔（小时）
        /// </summary>
        public int CleanupInterval { get; set; } = 24;

        /// <summary>
        /// 数据保留天数
        /// </summary>
        public int RetentionDays { get; set; } = 7;
    }

    /// <summary>
    /// 补偿配置
    /// </summary>
    public class CompensationConfiguration
    {
        /// <summary>
        /// 是否启用自动补偿
        /// </summary>
        public bool AutoCompensation { get; set; } = true;

        /// <summary>
        /// 补偿重试次数
        /// </summary>
        public int RetryCount { get; set; } = 3;

        /// <summary>
        /// 补偿重试间隔（毫秒）
        /// </summary>
        public int RetryInterval { get; set; } = 2000;

        /// <summary>
        /// 补偿超时时间（毫秒）
        /// </summary>
        public int Timeout { get; set; } = 30000;
    }

    /// <summary>
    /// 状态存储类型
    /// </summary>
    public enum StateStoreType
    {
        /// <summary>
        /// 内存存储
        /// </summary>
        InMemory,

        /// <summary>
        /// 文件存储
        /// </summary>
        File,

        /// <summary>
        /// 数据库存储
        /// </summary>
        Database,

        /// <summary>
        /// Redis存储
        /// </summary>
        Redis
    }

    /// <summary>
    /// 文件Saga状态存储选项
    /// </summary>
    public class FileSagaStateStoreOptions
    {
        /// <summary>
        /// 存储路径
        /// </summary>
        public string Path { get; set; } = "saga-state";

        /// <summary>
        /// 是否启用压缩
        /// </summary>
        public bool EnableCompression { get; set; } = true;

        /// <summary>
        /// 是否启用加密
        /// </summary>
        public bool EnableEncryption { get; set; } = false;

        /// <summary>
        /// 加密密钥
        /// </summary>
        public string? EncryptionKey { get; set; }
    }

    /// <summary>
    /// Saga初始化服务
    /// </summary>
    public class SagaInitializationService : IHostedService
    {
        private readonly ILogger<SagaInitializationService> _logger;
        private readonly IOptionsMonitor<SagaConfiguration> _configuration;
        private readonly IServiceProvider _serviceProvider;

        public SagaInitializationService(
            ILogger<SagaInitializationService> logger,
            IOptionsMonitor<SagaConfiguration> configuration,
            IServiceProvider serviceProvider)
        {
            _logger = logger;
            _configuration = configuration;
            _serviceProvider = serviceProvider;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config = _configuration.CurrentValue;
            
            if (!config.Enabled)
            {
                _logger.LogInformation("Saga mode is disabled");
                return Task.CompletedTask;
            }

            _logger.LogInformation("Saga mode is enabled with configuration: {@Config}", config);

            // 初始化状态存储
            using var scope = _serviceProvider.CreateScope();
            var stateStore = scope.ServiceProvider.GetRequiredService<ISagaStateStore>();
            
            try
            {
                // 这里可以添加状态存储的初始化逻辑
                _logger.LogInformation("Saga state store initialized successfully");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to initialize Saga state store");
                throw;
            }

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Saga initialization service is stopping");
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// Saga配置验证器
    /// </summary>
    public class SagaConfigurationValidator : IValidateOptions<SagaConfiguration>
    {
        public ValidateOptionsResult Validate(string? name, SagaConfiguration options)
        {
            var result = Validate(options);
            if (!result.IsValid)
            {
                return ValidateOptionsResult.Fail(string.Join("; ", result.Errors));
            }
            return ValidateOptionsResult.Success;
        }

        /// <summary>
        /// 验证Saga配置
        /// </summary>
        /// <param name="configuration">Saga配置</param>
        /// <returns>验证结果</returns>
        public static ValidationResult Validate(SagaConfiguration configuration)
        {
            var result = new ValidationResult();

            if (configuration == null)
            {
                result.AddError("Saga configuration cannot be null");
                return result;
            }

            if (configuration.DefaultTimeout <= 0)
            {
                result.AddError("Default timeout must be greater than 0");
            }

            if (configuration.DefaultRetryCount < 0)
            {
                result.AddError("Default retry count cannot be negative");
            }

            if (configuration.DefaultRetryInterval <= 0)
            {
                result.AddError("Default retry interval must be greater than 0");
            }

            // 验证状态存储配置
            if (configuration.StateStore == null)
            {
                result.AddError("State store configuration cannot be null");
            }
            else
            {
                if (configuration.StateStore.StoreType == StateStoreType.File && 
                    string.IsNullOrWhiteSpace(configuration.StateStore.FilePath))
                {
                    result.AddError("File path is required when using file state store");
                }

                if (configuration.StateStore.CleanupInterval <= 0)
                {
                    result.AddError("Cleanup interval must be greater than 0");
                }

                if (configuration.StateStore.RetentionDays <= 0)
                {
                    result.AddError("Retention days must be greater than 0");
                }
            }

            // 验证补偿配置
            if (configuration.Compensation == null)
            {
                result.AddError("Compensation configuration cannot be null");
            }
            else
            {
                if (configuration.Compensation.RetryCount < 0)
                {
                    result.AddError("Compensation retry count cannot be negative");
                }

                if (configuration.Compensation.RetryInterval <= 0)
                {
                    result.AddError("Compensation retry interval must be greater than 0");
                }

                if (configuration.Compensation.Timeout <= 0)
                {
                    result.AddError("Compensation timeout must be greater than 0");
                }
            }

            return result;
        }
    }

    /// <summary>
    /// 验证结果
    /// </summary>
    public class ValidationResult
    {
        /// <summary>
        /// 是否有效
        /// </summary>
        public bool IsValid => !Errors.Any();

        /// <summary>
        /// 错误列表
        /// </summary>
        public List<string> Errors { get; } = new();

        /// <summary>
        /// 添加错误
        /// </summary>
        /// <param name="error">错误信息</param>
        public void AddError(string error)
        {
            Errors.Add(error);
        }

        /// <summary>
        /// 添加错误列表
        /// </summary>
        /// <param name="errors">错误列表</param>
        public void AddErrors(IEnumerable<string> errors)
        {
            Errors.AddRange(errors);
        }
    }
}